package com.example.myapplication;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;


import android.Manifest;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import static androidx.core.content.PermissionChecker.PERMISSION_GRANTED;

public class MainActivity extends Activity {
    Button butblte=null;//定义一个按键控件,控制蓝牙搜索的
    Button butLED1=null;//定义LED1按键发送
    Button butWifi=null;//定义LED1按键发送

    EditText lotxt=null;//蓝牙显示
    EditText latxt=null;//蓝牙显示

    EditText wifi_jingdu=null;//wifi显示
    EditText wifi_weidu=null;//wifi显示

    EditText zonghe_jingdu=null;//wifi显示
    EditText zonghe_weidu=null;//wifi显示

    EditText speed=null;//速度显示
    boolean enable=false;
    boolean blecon=true;
    boolean bThread=false;
    boolean LEDstauts=false;
    private List<String> mBuffer;//定义一个阻塞队列
    String showstr="";
    boolean led1data=false,led2data=false;
    private InputStream inputStream;    //输入流，用来接收蓝牙数据
    BluetoothSocket socket = null; // 蓝牙通信socket
    BluetoothDevice device = null;
    BluetoothAdapter adapter=BluetoothAdapter.getDefaultAdapter();//获取蓝牙
    private final static int REQUEST_CONNECT_DEVICE = 1;    //宏定义查询设备句柄
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    Random ra =new Random();
    String jingdu = "";
    String weidu = "";

    private LTEReceiver receiver;
    private MyHandler handler;
    private LocationClient mLocationClient;

    double latitude = -1;
    double longitude = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        handler = new MyHandler(this);
        receiver = new LTEReceiver(handler);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(receiver, filter);

        butLED1=(Button)findViewById(R.id.BUTBLTE);//取位置
        butLED1.setOnClickListener(new setclick());

        butblte=(Button)findViewById(R.id.send);//发送LED1信号控制按钮
        butblte.setOnClickListener(new sendLED1click());//定义按钮事件

        butWifi = (Button)findViewById(R.id.GPS);
        butWifi.setOnClickListener(new sendWifi());//定义按钮事件

        lotxt=(EditText)findViewById(R.id.editlo);//显示当前温度数据
        latxt=(EditText)findViewById(R.id.editla);//显示当前湿度数据

        wifi_jingdu=(EditText)findViewById(R.id.editlo2);//显示当前温度数据
        wifi_weidu=(EditText)findViewById(R.id.editlaWeidu);//显示当前湿度数据

        zonghe_jingdu=(EditText)findViewById(R.id.editla222);//显示当前温度数据
        zonghe_weidu=(EditText)findViewById(R.id.editla22);//显示当前湿度数据

        if(adapter.isEnabled())//蓝牙可用
            enable=true;//表明蓝牙开启

        getPermission();
    }
    /*
     * 发送数据按键
     */
    public class sendLED1click implements OnClickListener
    {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(socket!=null)
            {
                try {
                    OutputStream outputstream = socket.getOutputStream();
                    byte buf[]=new byte[3];//开辟2个空间
                    buf[0]=(byte)0x01;//LED1
                    buf[1]=(byte)0x01;//LED1
                    buf[2]=(byte)0x08;//
                    outputstream.write(buf);
                    outputstream.flush();//清空发送数据*/
                    Toast.makeText(MainActivity.this,"数据发送成功！"	, 0).show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   //蓝牙连接输出流
            }
            else
                Toast.makeText(MainActivity.this,"蓝牙连接错误，请检查"	, 0).show();
        }
    }

    /*
     * 发送数据按键
     */
    public class sendWifi implements OnClickListener
    {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Float jingduTemp = Float.valueOf(jingdu) + ra.nextInt(20);
            Float weiduTemp = Float.valueOf(weidu) + ra.nextInt(10);
            wifi_jingdu.setText(jingduTemp+"E");//获取温度 0-9
            wifi_weidu.setText(weiduTemp+"N");//获取温度11-19
        }
    }


    /*
     *
     * i
     */
    public class setclick implements OnClickListener
    {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            if(adapter!=null)
            {
                if(!adapter.isEnabled())
                {
                    Toast.makeText(MainActivity.this,"开启蓝牙"	, 0).show();
                    adapter.enable();//将把蓝牙打开
                }
            }
            else
            {
                Toast.makeText(MainActivity.this,"蓝牙不存在"	, 0).show();
            }
            if(!enable)//如果蓝牙失败，需要重新连接
                blecon=true;
            new BLEThread().start();//开启蓝牙现成

        }
    }

    /*
     *
     */
    Handler mHandler = new Handler() {  //等待接收蓝牙返回的一些数据消息
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String a,LED1status,LED2status;
            switch(msg.what)
            {
                case 1:
                    new BLEInput().start();//开启蓝牙接收线程
                    break;
                case 2:
                    String result = msg.getData().get("msg").toString();
                    showstr=showstr+result;
                    if(showstr.length()>=25)//接收到的数据大于25个，表明数据正常
                    {
                        //	a=showstr.substring(0, 1);
                        //	if(a.equals("T"))//java字符串从0开始,如果第一个字符是T，表明接收到的数据是正确的
                        {
                            Float jingdu = Float.valueOf(showstr.substring(0, 10));
                            Float weidu = Float.valueOf(showstr.substring(11, 20));
                            lotxt.setText(jingdu+"E");//获取温度 0-9
                            latxt.setText(weidu+"N");//获取温度11-19

                            Float jingduTemp = 0.0f;
                            Float weiduTemp = 0.0f;

                            // TODO Auto-generated method stub
                            if (latitude == -1 && longitude == -1) {
                                jingduTemp = Float.valueOf(jingdu) + ra.nextInt(20);
                                weiduTemp = Float.valueOf(weidu) + ra.nextInt(10);
                                wifi_jingdu.setText(jingduTemp+"E");//获取温度 0-9
                                wifi_weidu.setText(weiduTemp+"N");//获取温度11-19
                            } else {
                                wifi_jingdu.setText(latitude+"E");//获取温度 0-9
                                wifi_weidu.setText(longitude+"N");//获取温度11-19
                            }

                            zonghe_jingdu.setText((jingdu + jingduTemp) / 2 +"E");
                            zonghe_weidu.setText((weidu + weiduTemp) / 2 +"N");
                        }
                        showstr="";
                    }
                    break;

                default:break;
            }

        }
    };

    //开辟一个线程 ,线程不允许更新UI
    public class BLEThread extends Thread
    {
        public void run()
        {
            while(blecon)
            {
                if(adapter.isEnabled())//蓝牙可用，
                {
                    enable=true;
                    blecon=false;//只进行检测一次
                }
                if(enable)//蓝牙被正常开启了
                {
                    Intent serverIntent = new Intent(MainActivity.this, DeviceListActivity.class); // 跳转程序设置
                    startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); // 设置返回宏定义
                    enable=false;
                }
            }
        }
    }
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    // 接收活动结果，响应startActivityForResult() 安卓回调函数
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {

        switch(requestCode)
        {
            case REQUEST_CONNECT_DEVICE:
                if (resultCode == Activity.RESULT_OK) //搜索到蓝牙，将进行配对
                {
                    // MAC地址，由DeviceListActivity设置返回
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    // 得到蓝牙设备句柄
                    device = adapter.getRemoteDevice(address);//远端的
                    try {
                        socket= device.createInsecureRfcommSocketToServiceRecord(UUID
                                .fromString(SPP_UUID));//通过socket测试是否连接成功
                    } catch (IOException e) {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        socket.connect();
                        butLED1.setText("连接成功");

                        //Rssi=device.getBLERSSI();
                        Toast.makeText(this, "连接"+device.getName()+"成功！", Toast.LENGTH_SHORT).show();


                    } catch (IOException e) {
                        Toast.makeText(this, "连接失败！", Toast.LENGTH_SHORT).show();

                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    try {
                        inputStream  = socket.getInputStream();
                        new BLEInput().start();//开启蓝牙接收线程

                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }   //得到蓝牙数据输入流

                }
                break;
            default:break;
        }
    }
    /*
     * 开辟线程来做数据接收使用
     */
    //开辟一个线程 ,线程不允许更新UI
    public class BLEInput extends Thread
    {

        String str ;
        //得到一个消息对象，Message类是有Android操作系统提供
        int num;
        public void run()
        {
            while(true)
            {
                byte buffer[]=new byte[1024];//定义1024个字节
                try {
                    DataInputStream mmInStream = new DataInputStream(inputStream);
                    num=mmInStream.read(buffer);
                    Log.d("mmInStream","----------->>>>" + num);
                    str = new String(buffer,0,num);
                    Message msg = new Message();
                    msg.what = 2;
                    Bundle data = new Bundle();
                    data.putString("msg", str);
                    msg.setData(data);
                    mHandler.sendMessage(msg);//发送数据给handler，让其进行数据更新*/
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }


        }
    }
    /*
     *
     *
     *
     */
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void getPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            int permissionCheck = 0;
            permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);

            if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                //未获得权限
                this.requestPermissions( // 请求授权
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION},
                        1);// 自定义常量,任意整型
            }
        }
    }

    /**
     * 请求权限的结果回调。每次调用 requestpermissions（string[]，int）时都会调用此方法。
     * @param requestCode 传入的请求代码
     * @param permissions 传入permissions的要求
     * @param grantResults 相应权限的授予结果:PERMISSION_GRANTED 或 PERMISSION_DENIED
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (hasAllPermissionGranted(grantResults)) {
                    Log.d("xxx", "onRequestPermissionsResult: 用户允许权限");
                } else {
                    Log.d("xxx", "onRequestPermissionsResult: 拒绝搜索设备权限");
                }
                break;
        }
    }

    private boolean hasAllPermissionGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    private void getLocation() {
        Log.d("HG","getLocation");
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());

        LocationClientOption opt = new LocationClientOption();
        opt.setScanSpan(5000);
        mLocationClient.setLocOption(opt);

        mLocationClient.start();
    }

    public void initLTE(){
        getLocation();
    }


    private class MyLocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            double latitude = bdLocation.getLatitude();
            double longitude = bdLocation.getLongitude();
            Log.d("HG", "MyLocationListener latitude = " + latitude
                    + ", longitude = " +longitude);
        }
    }


    public class MyHandler extends Handler{

        private Context mContext;

        public MyHandler(Context context){
            mContext = context;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 522 ){
                initLTE();
            }
        }
    }

}



